const WxPay = require('weixin-pay');
const getConfig = require('./configUtil').getConfig;
const fs = require('fs');
const path = require('path');
const certPath = path.join(__dirname, '../config/apiclient_cert.pem');
const keyPath = path.join(__dirname, '../config/apiclient_key.pem');
const request = require('request');

class MyWxPay {
    constructor() {
        this.appid = getConfig.wechat.appId;
        this.mch_id = getConfig.wechat.mchId;
        this.partner_key = getConfig.wechat.mchSecret; // 微信商户平台API密钥
        // pfx: fs.readFileSync('./wxpay_cert.p12'), // 微信商户平台证书
        this.wx = WxPay({
            appid: this.appid,
            mch_id: this.mch_id,
            partner_key: this.partner_key, // 微信商户平台API密钥
            // pfx: fs.readFileSync(certPath), // 微信商户平台证书
        });
    }

    refund(order, fn) {
        if (!(order.transaction_id || order.out_refund_no)) {
            fn(null, { return_code: 'FAIL', return_msg:'缺少参数' });
        }
        const util = this.wx.Util;
        order.nonce_str = order.nonce_str || util.generateNonceString();
        util.mix(order, { appid:this.appid, mch_id:this.mch_id });
        order.sign = this.wx.sign(order);
        request({
            url: "https://api.mch.weixin.qq.com/secapi/pay/refund",
            method: "POST",
            body: util.buildXML({xml: order}),
            agentOptions: {
                cert: fs.readFileSync(certPath),
                key: fs.readFileSync(keyPath)
            }
        }, function(err, response, body){
            util.parseXML(body, fn);
        });
    }

    withDraw(order, fn) {
        const util = this.wx.Util;
        order.nonce_str = order.nonce_str || util.generateNonceString();
        util.mix(order, { mch_appid:this.appid, mchid:this.mch_id });
        order.sign = this.wx.sign(order);
        request({
            url: "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers",
            method: "POST",
            body: util.buildXML({xml: order}),
            agentOptions: {
                cert: fs.readFileSync(certPath),
                key: fs.readFileSync(keyPath)
            }
        }, function(err, response, body){
            util.parseXML(body, fn);
        });
    }
}

module.exports = MyWxPay;

